﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Api.Write.Controllers;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ApiResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<UsersModel> _userRepository;
        public DeleteUserHandler(IMapper mapper, IBaseRepository<UsersModel> userRepository)
        {
            _mapper = mapper;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var user = _userRepository.GetAll().Where(x=>x.IsDelete == false && x.Id==request.Id).FirstOrDefault();
            if (user != null)
            {
                user.IsDelete= true;    
            }
            var res =_userRepository.Update(user);
            if (res > 0)
            {
                result.Code =StatusEnum.OK;
                result.Data = res;
                result.Message = "删除成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "删除失败";
            }
            return Task.FromResult(result);
        }
    }
}
